package com.cby.android.olive.ext

import android.graphics.drawable.Drawable
import android.os.Build
import android.view.View
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import com.cby.android.olive.tool.GrayManager


fun View.show() {
    this.visibility = View.VISIBLE
}

fun View.inShow() {
    this.visibility = View.INVISIBLE
}

fun View.hide() {
    this.visibility = View.GONE
}

fun View.setShow(block: () -> Unit) {
    block.invoke()
    this.visibility = View.VISIBLE
}

fun View.setHide(block: () -> Unit) {
    block.invoke()
    this.visibility = View.GONE
}

/**
 * 同一个的view，展示和隐藏的拓展变量
 */
var View.isVisible: Boolean
    get() = this.visibility == View.VISIBLE
    set(value) {
        this.visibility = if(value) View.VISIBLE else View.GONE
    }

fun View.setShow(show:Boolean, block: (() -> Unit?)? = null) {
    if(show) {
        if (block != null) {
            block()
        }
        this.visibility = View.VISIBLE
    }else{
        this.visibility = View.GONE
    }
}

/**
 * 设置背景图，保持原有的内间距不变
 *
 * @receiver View
 * @param resId Int
 */
fun View.setBackgroundKeepingPadding(@DrawableRes resId: Int) {
    val drawable = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        context.getDrawable(resId)
    } else {
        resources.getDrawable(resId)
    }
    if (drawable != null) {
        setBackgroundKeepingPadding(drawable)
    }
}

/**
 * 设置背景图，保持原有的内间距不变
 *
 * @receiver View
 * @param drawable Drawable
 */
fun View.setBackgroundKeepingPadding(drawable: Drawable) {
    val padding = intArrayOf(
        paddingLeft, paddingTop, paddingRight,
        paddingBottom
    )
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        background = drawable
    } else {
        setBackgroundDrawable(drawable)
    }
    setPadding(padding[0], padding[1], padding[2], padding[3])
}

/**
 * 集合view的内联拓展函数
 */
inline fun List<View>.doOnClick(crossinline block: () -> Unit) =
    forEach { it.doOnClick(block) }

inline fun View.doOnClick(crossinline block: () -> Unit) =
    setOnClickListener { block() }

inline fun List<View>.doOnLongClick(crossinline block: () -> Unit) =
    forEach { it.doOnLongClick(block) }

inline fun View.doOnLongClick(crossinline block: () -> Unit) =
    setOnLongClickListener {
        block()
        true
    }

/**
 * 设置view置灰色
 */
fun View.setGray() {
    GrayManager.setLayerGrayType(this)
}

